package com.mhl.campuscabinet;

import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import android.widget.Toolbar;

import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.mhl.adapter.MessageAdapter;
import com.mhl.entity.Message;

import java.util.ArrayList;
import java.util.List;

public class MessageFragment extends Fragment {

    private List<Message> messageList = new ArrayList<>();
    private MainActivity activity;
    private MessageAdapter adapter;
    private RecyclerView recyclerView;
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_message, container, false);
        // 配置recyclerView
        recyclerView = view.findViewById(R.id.recycle_view);
        // 线性布局管理器
        LinearLayoutManager layoutManager = new LinearLayoutManager(getActivity());
        recyclerView.setLayoutManager(layoutManager);
        // 测试
        test();
        // 加载历史消息并即开始监听新消息
        loadMessage();
        // 内容适配器
        activity = (MainActivity) getActivity();
        adapter = new MessageAdapter(messageList, activity);
        recyclerView.setAdapter(adapter);


        // Inflate the layout for this fragment
        return view;
    }

    // 先简单加载一个消息
    public void test() {
        Message message = new Message("1",
                "https://img0.baidu.com/it/u=1697496574,2494610909&fm=26&fmt=auto",
                "ChatRoom","有新消息");
        messageList.add(message);
    }

    public void loadMessage() {
        // 请先加载数据库中发给本用户的历史消息
        //1. get self user

        //2. 请求服务器，只发userId，
        // 再新开启一个端口，用webSocket监听新的消息
        // 并把接收到的Message装配好方进messageList里

        // 这是最后要做的事情，一旦有新消息，请把这句话放到最后，用于通知内容适配器更新UI
        new Handler().post(new Runnable() {
            @Override
            public void run() {
                adapter.notifyDataSetChanged();
            }
        });

    }
}